from flask import Flask, make_response, jsonify, g, current_app as app,Blueprint,request
from sqlalchemy import select,insert,update,func,join
from sqlalchemy.sql import text
from eim.tools.dbtool import DBTool
from eim import db
from eim.tools.searchtool import SearchCondition,SearchConditionList,MatchLogic,PartnerRS
from eim.result.simple_result import SimpleResult

powerbp=Blueprint("powerbp","powerbp",__name__,url_prefix="/power")

@powerbp.route("/append",methods=['PUT'])
def appendNewPower():
    """
    增加新的功能
    """
    try:
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("新增系统功能所提交的参数格式不正确")
        keys = pms
        if('pname' not in keys) or ('powertype' not in keys) or ('parent' not in keys) or ('powerowner' not in keys) or ('URL' not in keys):
            raise Exception("缺少必要的参数,请查阅API文档调整调用方法")
        from eim.Services.powerService import PowerService
        pws = PowerService(db)
        id = pws.append(pms["pname"],pms["powertype"],pms["parent"],pms["powerowner"],pms["URL"])
        return SimpleResult(status='T',value=id).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()


@powerbp.route("/upgrade/<int:id>",methods=['POST'])
def upgrade(id:int):
    """
    更新系统信息条目
    """
    try:
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("更新系统功能条目所提交的信息格式不正确")
        from eim.Services.powerService import PowerService
        pws = PowerService(db)
        id = pws.upgrade(id,pms)
        return SimpleResult(status='T',value=id).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@powerbp.route("/alltree",methods=['POST'])
def powerTree():
    """
    获取系统功能菜单的属性结构
    """
    try:
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("获取系统功能树时提供的参数格式不正确")
        from eim.Services.powerService import PowerService
        pws = PowerService(db)
        con = db.engine.connect()
        tree = pws.getPowerTree(con,pms)
        return SimpleResult(status='T',value=tree).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@powerbp.route("/delete/<int:id>",methods=["DELETE"])
def deletePower(id:int):
    """
    删除指定id的系统功能条目

    Args:
        id (int): 待删除功能条目的id
    """
    try:
        from eim.Services.powerService import PowerService
        pws = PowerService(db)
        rc = pws.deletePowerByID(id)
        return SimpleResult(status='T',value=rc).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@powerbp.route("/rolePowerAuth/<roleCode>",methods=["GET"])
def getRolePowerAuthorize(roleCode:str):
    """
    通过角色编号获取角色授权

    Args:
        rolecode (str): 角色编号
    """
    try:
        from eim.Services.powerService import PowerService
        pws = PowerService(db)
        rc = pws.getRoleOptionsAuthStatus(roleCode)
        return SimpleResult(status="T",value=rc).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
   
@powerbp.route("/appendPowerOperate",methods=["PUT"]) 
def appendPowerOperate():
    """
    为指定的角色添加操作
    """
    try:
        pms = request.json
        keys= pms.keys()
        if("pcode" not in keys)or("oname" not in keys):
            raise Exception("缺少功能编码和操作名称参数")
            
        from eim.Services.powerService import PowerService
        pws = PowerService(db)
        rcount = pws.appendPowerOperate(pms["pcode"],pms["oname"])
        return SimpleResult(status="T",value=rcount).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@powerbp.route("/getRoleAuthorizes",methods=["GET"])
def getRoleAuthorizes():
    """
    获取所有角色的功能操作授权,用于权限配置
    """
    try:
        from eim.Services.powerService import PowerService
        pws = PowerService(db)
        return SimpleResult(status='T',value=pws.getAllRoleAuthStatus()).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@powerbp.route("/getRoleAuthByRoleInfo/<rcode>",methods=["GET"])
def getRoleAuthByRoleInfo(rcode:str):
    """
    获取指定角色编码的权限
    """
    try:
        from eim.Services.powerService import PowerService
        pws = PowerService(db)
        v = pws.getRoleOptionsAuthStatus(rcode)
        return SimpleResult(status='T',value=v).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()

    
@powerbp.route("/getroleauth",methods=["GET"]) 
def powertest():
    """
    系统功能接口测试
    """
    from eim.Services.powerService import PowerService
    pws = PowerService(db)
    rs={
        "res":"auth",
        "value": pws.getRoleOptionsAuthStatus()
    }
    return rs

@powerbp.route("/saveRoleAuthorize",methods=["POST"])
def saveRoleAuthorize():
    """
    保存角色授权
    """
    try:
        from eim.Services.powerService import PowerService
        ps = PowerService(db)
        auths = request.json
        rcode = auths["rcode"]
        for power in auths["powerauth"]:
            for opt in power["opts"]:
                ef = opt["editflag"]
                ocode = opt["ocode"]
                authorize=opt["authorize"]
                if(ef=="insert"):
                    ps.insertRoleAuthorize(rcode,ocode,authorize)
                else:
                    ps.upgradeRoleAuthorize(rcode,ocode,authorize)
        return SimpleResult(status="T",value="1").toDict()
    except Exception as error:
        info = str(error)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()

@powerbp.route("/getPowerTreeByRoleCode/<rolecode>",methods=["GET"])
def getPowerTreeByRoleCode(rolecode:str):
    """
    通过角色编号获取功能菜单树
    Args:
        rolecode (str): 角色编码
    """
    try:
        from eim.Services.powerService import PowerService
        ps = PowerService(db)
        con = db.engine.connect()
        pm={}
        ptree = ps.getPowerTree(con,pm)
        auopts = ps.getRoleOptionsAuthStatus(rolecode)
        t= ps.getPowerTreeByRole(ptree,auopts)
        return SimpleResult(status="T",value=t).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()